const randomCenter = function(bounds, range) {
    let { x: minX, y: minY, w: width, h: height } = bounds;  
    let centerX = minX + width / 2;  
    let centerY = minY + height / 2;  
    let randomXCenter = Math.random() * (2 * range) - range + centerX;  
    let randomYCenter = Math.random() * (2 * range) - range + centerY;  
    return { x: randomXCenter, y: randomYCenter };  
}
const bottomCenter = function(bounds) {
    return {
        x: bounds.x + bounds.w / 2,
        y: bounds.y + bounds.h
    }
}
const angleCalcul = function(source, target) {
    let dx = target.x - source.x    
    let dy = target.y - source.y    
    let radAngle = Math.atan2(dy, dx)  
    let degAngle = radAngle * (180 / Math.PI)
    return ((degAngle + 360) % 360) 
}
const distanceCalcul = function(source, targets) {
    let distances = []
    let sourceCenter = bottomCenter(source)
    for (let index = 0; index < targets.length; index++) {
        let target = targets[index]
        let targetCenter = bottomCenter(target)
        distances.push({
            target: target,
            sourceCenter: sourceCenter,
            targetCenter: targetCenter,
            distance: Math.sqrt(Math.pow(targetCenter.x - sourceCenter.x, 2) + Math.pow(targetCenter.y - sourceCenter.y, 2))
        })
    }
    return distances 
}
const suitableTarget = function(targets) {
    if (!targets || targets.length == 0) {
        return null
    }
    let maxProbItem = null;
    let maxProb = -Infinity; 

    for (let i = 0; i < targets.length; i++) {
        const target = targets[i];
        if (target.prob > maxProb) {
            maxProb = target.prob;
            maxProbItem = target;
        }
    }
    return maxProbItem;
}
const findClosest = function(source, targets) {
    if (!source || !targets || targets.length == 0) {
        return
    }
    let closestResult = {distance: 999999}
    let distances = distanceCalcul(source, targets)
    for (let d of distances) {
        if (closestResult["distance"] < d.distance) {
            continue
        }
        closestResult["distance"] = d.distance
        closestResult["angle"] = angleCalcul(d.sourceCenter, d.targetCenter); 
        closestResult["target"] = d.target
        closestResult["p1"] = d.sourceCenter
        closestResult["p2"] = d.targetCenter
    }
    return closestResult
}
const calculRoute = function(source, targets, lastest) {
    if (!source || !source.x || !source.y) {
        return
    }  
    // 辅助函数：计算两点之间的距离  
    function distance(p1, p2) {  
        const dx = p2.x - p1.x;  
        const dy = p2.y - p1.y;  
        return Math.sqrt(dx * dx + dy * dy);  
    }  
  
    // 辅助函数：计算中心点  
    function getCenter(target) {  
        return {  
            x: target.x + target.w / 2,  
            y: target.y + target.h / 2  
        };  
    }  
  
    // 辅助函数：计算两点之间的角度（弧度）  
    function angle(p1, p2) {  
        let radAngle = Math.atan2(p2.y - p1.y, p2.x - p1.x);  
        let degAngle = radAngle * (180 / Math.PI)
        return ((degAngle + 360) % 360) 
    }  
  
    // 排序 targets  
    targets.sort((a, b) => getCenter(a).y - getCenter(b).y);  
  
    // 初始化结果数组  
    let result = [];  
    let sourceCenter = bottomCenter(source)
    // 计算 source 到第一个 target 的距离和角度  
    let firstCenter = getCenter(targets[0]);  
    result.push({  
        distance: distance(sourceCenter, firstCenter),  
        angle: angle(sourceCenter, firstCenter)  
    });  
  
    // 依次计算相邻 target 之间的距离和角度  
    for (let i = 1; i < targets.length; i++) {  
        let prevCenter = getCenter(targets[i - 1]);  
        let currCenter = getCenter(targets[i]);  
        result.push({  
            distance: distance(prevCenter, currCenter),  
            angle: angle(prevCenter, currCenter)  
        });  
    }  
    if (lastest != undefined) {
        result.push({
            distance: distance(getCenter(targets[targets.length - 1]), getCenter(lastest)),  
            angle: angle(getCenter(targets[targets.length - 1]), getCenter(lastest))  
        })
    }
    return result;  
}  
  
// 示例使用  
const source = { x: 0, y: 0 };  
const targets = [  
    { x: 1, y: 1, w: 1, h: 1 },  
    { x: 2, y: 3, w: 1, h: 1 },  
    { x: 0, y: 5, w: 1, h: 1 }  
];  
  
console.log(calculRoute(source, targets));
const calculP = function(targets, direct) {
    if (targets == undefined) {
        return targets
    }
    for (let t of targets) {
        if (direct == "1") {
            t.y = t.y + 50
        }
        if (direct == "2") {
            t.x = t.x + 50
        }
        if (direct == "3") {
            t.y = t.y - 50
        }
        if (direct == "4") {
            t.x = t.x - 50
        }
    }
    return targets
} 
const findFarthest = function(source, targets) {
    console.info("source:" + JSON.stringify(source) + ",target:" + JSON.stringify(targets))
    if (!source || !targets) {
        return
    }
    let farthestResult = {distance: 0}
    let distances = distanceCalcul(source, targets)
    console.log("计算距离:" + JSON.stringify(distances))
    for (let d of distances) {
        if (farthestResult["distance"] > d.distance) {
            continue
        }
        farthestResult["distance"] = d.distance
        farthestResult["angle"] = angleCalcul(d.sourceCenter, d.targetCenter); 
        farthestResult["target"] = d.target
        farthestResult["p1"] = d.sourceCenter
        farthestResult["p2"] = d.targetCenter
    }
    return farthestResult
}
const rockerCoordinate = function(rocker, angleInDegrees) {
    if (angleInDegrees == undefined || angleInDegrees == NaN) {
        return null
    }
    let centerX = rocker.x + Math.round(rocker.w / 2)
    let centerY = rocker.y + Math.round(rocker.h / 2)
    let random = 155 - Math.floor(Math.random() * 10)
    console.log(centerX)
    console.log(centerY)
    console.log(random)
    if (angleInDegrees == 0 || angleInDegrees == 360) {
        return {x: random + centerX, y: centerY}
    } else if (angleInDegrees == 90) {
        return {x: centerX, y: random + centerY}
    } else if (angleInDegrees == 180) {
        return {x: -random + centerX, y: centerY}
    } else if (angleInDegrees == 270) {
        return {x: centerX, y: -random + centerY}
    }
    console.log("angleInDegrees:" + angleInDegrees)
    var angleInRadians = angleInDegrees * (Math.PI / 180);
    console.log("angleInRadians:" + angleInRadians)
    if ((angleInDegrees > 0 && angleInDegrees <= 45) || angleInDegrees >= 315) {
        return {x: random + centerX, y: random * Math.tan(angleInRadians) + centerY}
    } else if (angleInDegrees > 45 && angleInDegrees <= 135) {
        return {x: random / Math.tan(angleInRadians) + centerX, y: random + centerY}
    } else if (angleInDegrees > 135 && angleInDegrees <= 225) {
        return {x: -random + centerX, y: -random * Math.tan(angleInRadians) + centerY}
    } else {
        return {x: -random / Math.tan(angleInRadians) + centerX, y: -random + centerY}
    }
}
exports.distanceCalcul = distanceCalcul
exports.calculP = calculP
exports.randomCenter = randomCenter
exports.suitableTarget = suitableTarget
exports.findClosest = findClosest
exports.findFarthest = findFarthest
exports.rockerCoordinate = rockerCoordinate
exports.calculRoute = calculRoute
